package cn.com.citydo.base.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author jh
 * @date 2019/5/21 11:27
 * @Description: 全局异常处理
 */

@ControllerAdvice(annotations = RestController.class)
public class ExceptionAdvice {
	private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public ResponseResult handleExp(Exception e) {
		logger.error("Unknown Exception: {}", e);
		return ResponseResult.builder().code(ErrorCodeEnum.SYSTEM_SERVER_ERROR.getCode()).msg(ErrorCodeEnum.SYSTEM_SERVER_ERROR.getMsg()+ ":" +e.getMessage()).build();
	}

	@ExceptionHandler(BizException.class)
	@ResponseBody
	public ResponseResult handleBizExp(BizException e) {
		logger.error("Biz Exception: {}", e.getMessage());
		return ResponseResult.builder().code(e.getErrorCode()).msg(e.getMessage()).build();
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public ResponseResult handleMethodArgumentNotValidExp(MethodArgumentNotValidException e) {
		FieldError error = (FieldError)e.getBindingResult().getAllErrors().get(0);
		StringBuilder sb = new StringBuilder();
		String errorMsg = sb.append(error.getField()).append("(").append(error.getRejectedValue()).append(")")
				.append(" : ").append(error.getDefaultMessage()).toString();
		logger.error("MethodArgumentNotValid Exception: {}", errorMsg);
		return ResponseResult.builder().code(ErrorCodeEnum.SYSTEM_PARAMS_ERROR.getCode()).msg(e.getMessage()).build();
	}
}
